"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "../../contexts/LanguageContext";
import { CreateTokenForm } from "../../components/CreateTokenForm";
import { TokenList } from "../../components/TokenList";
import { useWebSocket } from "../../hooks/useWebSocket";
import { PixelHeader } from "../../components/PixelHeader";
import { NetworkDiagnostic } from "../../components/NetworkDiagnostic";
import { WalletDebugInfo } from "../../components/WalletDebugInfo";
import { ChatRoom } from "../../components/ChatRoom";

export default function SolanaPage() {
  const { t } = useLanguage();
  const [activeTab, setActiveTab] = useState<"list" | "create">("list");
  const [chatOpen, setChatOpen] = useState(false);
  const { connecting } = useWebSocket();
  const [stats, setStats] = useState<{
    totalTokens: number;
    totalVolume: number;
    activeTraders: number;
  } | null>(null);
  const [mounted, setMounted] = useState(false);
  const [showDebug] = useState(false);

  // 防止水合错误
  useEffect(() => {
    setMounted(true);
  }, []);

  // 获取统计数据
  useEffect(() => {
    const fetchStats = async () => {
      try {
        const apiUrl =
          process.env.NEXT_PUBLIC_API_URL || "http://localhost:7172/api";
        const response = await fetch(`${apiUrl}/tokens/stats`);
        if (response.ok) {
          const result = await response.json();

          if (result.success && result.data) {
            setStats({
              totalTokens: result.data.totalTokens,
              totalVolume: result.data.totalVolume,
              activeTraders: result.data.activeTraders,
            });
          }
        } else {
          console.error("API 响应错误:", response.status);
          // 使用默认值
          setStats({
            totalTokens: 0,
            totalVolume: 0,
            activeTraders: 0,
          });
        }
      } catch (error) {
        console.error("获取统计数据失败:", error);
        // 使用默认值
        setStats({
          totalTokens: 0,
          totalVolume: 0,
          activeTraders: 0,
        });
      }
    };

    if (mounted) {
      fetchStats();
    }
  }, [mounted]);

  if (!mounted) {
    return (
      <div className="min-h-screen bg-gray-900 flex items-center justify-center">
        <div className="text-white">Loading...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen" style={{ background: "var(--background)" }}>
      <PixelHeader />

      {/* 主内容 */}
      <main className="app-container py-8">
        {/* 标题和统计 */}
        <div className="text-center mb-12 w-full" id="tokens">
          <h1 className="text-4xl md:text-6xl font-bold text-white mb-4 font-pixel">
            {t("title")}
          </h1>
          <p
            className="text-lg md:text-xl mb-8 font-body"
            style={{ color: "var(--foreground)" }}
          >
            {t("subtitle")}
          </p>

          {/* 统计数据 */}
          {stats && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 w-full mx-auto mb-8 text-center">
              <div className="pixel-card p-6 text-center w-full">
                <div
                  className="text-2xl font-bold"
                  style={{ color: "var(--primary)" }}
                >
                  {stats.totalTokens}
                </div>
                <div style={{ color: "var(--foreground)" }}>
                  {t("stats.totalTokens")}
                </div>
              </div>
              <div className="pixel-card p-6 text-center w-full">
                <div
                  className="text-2xl font-bold"
                  style={{ color: "var(--secondary)" }}
                >
                  {stats.totalVolume}
                </div>
                <div style={{ color: "var(--foreground)" }}>
                  {t("stats.totalVolume")}
                </div>
              </div>
              <div className="pixel-card p-6 text-center w-full">
                <div
                  className="text-2xl font-bold"
                  style={{ color: "var(--accent)" }}
                >
                  {stats.activeTraders}
                </div>
                <div style={{ color: "var(--foreground)" }}>
                  {t("stats.activeTraders")}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 网络诊断 */}
        <div className="max-w-4xl mx-auto">
          <NetworkDiagnostic />
        </div>

        {/* 调试信息切换 */}
        {/* {walletConnected && (
          <div className="mb-4 text-center">
            <button
              onClick={() => setShowDebug(!showDebug)}
              className="pixel-btn text-sm"
            >
              {showDebug ? '隐藏调试信息' : '显示调试信息'}
            </button>
          </div>
        )} */}

        {/* 钱包调试信息 */}
        {showDebug && <WalletDebugInfo />}

        {/* 标签页 */}
        <div className="app-container mb-8 " id="create">
          <br />
          <div className=" w-full">
            <div className="flex justify-center gap-2">
              <button
                onClick={() => setActiveTab("list")}
                className={`px-6 py-2 transition-colors ${
                  activeTab === "list"
                    ? "pixel-btn"
                    : "pixel-btn bg-gray-600 hover:bg-gray-500"
                }`}
              >
                {t("navigation.tokenList")}
              </button>

              <button
                onClick={() => setActiveTab("create")}
                className={`px-6 py-2 transition-colors ${
                  activeTab === "create"
                    ? "pixel-btn"
                    : "pixel-btn bg-gray-600 hover:bg-gray-500"
                }`}
              >
                {t("createToken.title")}
              </button>
            </div>
          </div>
        </div>
        <br />

        <div className="w-full">
          {activeTab === "list" ? <TokenList /> : <CreateTokenForm />}
        </div>

        <ChatRoom isOpen={chatOpen} onToggle={() => setChatOpen(!chatOpen)} />

        {connecting && (
          <div className="fixed bottom-4 left-4 bg-yellow-600 text-white px-4 py-2 rounded-lg">
            connecting to realtime server...
          </div>
        )}
      </main>
    </div>
  );
}
